package com.demo.function.office.word;

import fr.opensagres.poi.xwpf.converter.pdf.PdfOptions;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;

@Slf4j
public class WordFunction {

    private static final String temp = "temp";

    /**
     * word文档转图片，通过比较迂回方法进行转换。首先将word转pdf，再将pdf转图片
     * @param params
     */
    public void wordToImg(Map<String, String> params) {
        ClassPathResource classPathResource = new ClassPathResource("template" + File.separator + "word.docx");
        log.info("path:{}", classPathResource.getPath());

        // docx转pdf
        File pdf;
        File png;
        try {
            pdf = File.createTempFile(temp, ".pdf");
            png = File.createTempFile(temp, ".png");
        } catch (IOException e) {
            log.error("", e);
            throw new RuntimeException(e);
        }

        try (InputStream source = classPathResource.getInputStream();
             OutputStream target = new FileOutputStream(pdf.getPath())) {

            PdfOptions options = PdfOptions.create();
            // word转pdf
            WordUtil.wordConverterToPdf(source, target, options, params);
            // pdf转图片
            PdfUtil.pdfToImage(pdf.getPath(), png.getPath());
            log.info("png图片路径：{}", png.getPath());
        } catch (Exception e) {
            log.error("", e);
            throw new RuntimeException(e);
        }
    }
}
